/**
 * 项目管理器
 * 负责项目的CRUD操作和业务逻辑
 */
class ProjectManager {
  constructor(dataStorage) {
    this.dataStorage = dataStorage;
  }

  /**
   * 初始化项目管理器
   */
  init() {
    console.log('[Switcher3] 项目管理器初始化');
    
    // 确保数据存储已初始化
    this.dataStorage.ensureConfig();
    
    // 恢复上次的激活状态
    this.restoreActiveEnvironments();
  }

  /**
   * 恢复激活的环境状态
   */
  async restoreActiveEnvironments() {
    try {
      const activeEnvironments = this.dataStorage.getActiveEnvironments();
      console.log(`[Switcher3] 恢复 ${activeEnvironments.length} 个激活环境`);
      
      // 使用Whistle的rulesServer机制，不需要手动激活
      // 规则会在rulesServer中动态生成
    } catch (error) {
      console.error('[Switcher3] 恢复环境状态失败:', error);
    }
  }

  /**
   * 获取项目列表
   */
  getProjectList() {
    try {
      const projects = this.dataStorage.getProjectList();
      console.log(`[Switcher3] 获取项目列表，共 ${projects.length} 个项目`);
      console.log('[Switcher3] 项目列表详情:', projects);
      return {
        success: true,
        data: projects
      };
    } catch (error) {
      console.error('[Switcher3] 获取项目列表失败:', error);
      return {
        success: false,
        message: `获取失败: ${error.message}`
      };
    }
  }

  /**
   * 获取项目详情
   */
  getProject(projectId) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      console.log(`[Switcher3] 获取项目详情: ${project.name}`);
      return {
        success: true,
        data: project
      };
    } catch (error) {
      console.error('[Switcher3] 获取项目详情失败:', error);
      return {
        success: false,
        message: `获取失败: ${error.message}`
      };
    }
  }

  /**
   * 创建项目
   */
  createProject(name) {
    try {
      if (!name || !name.trim()) {
        return {
          success: false,
          message: '项目名称不能为空'
        };
      }

      name = name.trim();
      
      // 检查项目名称是否已存在
      const existingProjects = this.dataStorage.getProjectList();
      if (existingProjects.some(p => p.name === name)) {
        return {
          success: false,
          message: '项目名称已存在'
        };
      }

      const project = this.dataStorage.createProject(name);
      console.log(`[Switcher3] 创建项目成功: ${name}`);
      
      return {
        success: true,
        data: project,
        message: '项目创建成功'
      };
    } catch (error) {
      console.error('[Switcher3] 创建项目失败:', error);
      return {
        success: false,
        message: `创建失败: ${error.message}`
      };
    }
  }

  /**
   * 重命名项目
   */
  renameProject(projectId, newName) {
    try {
      if (!newName || !newName.trim()) {
        return {
          success: false,
          message: '项目名称不能为空'
        };
      }

      newName = newName.trim();
      
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      // 检查新名称是否已存在
      const existingProjects = this.dataStorage.getProjectList();
      if (existingProjects.some(p => p.id !== projectId && p.name === newName)) {
        return {
          success: false,
          message: '项目名称已存在'
        };
      }

      this.dataStorage.updateProject(projectId, { name: newName });
      console.log(`[Switcher3] 项目重命名成功: ${project.name} -> ${newName}`);
      
      return {
        success: true,
        message: '项目重命名成功'
      };
    } catch (error) {
      console.error('[Switcher3] 重命名项目失败:', error);
      return {
        success: false,
        message: `重命名失败: ${error.message}`
      };
    }
  }

  /**
   * 删除项目
   */
  deleteProject(projectId) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      // 先停用环境
      this.dataStorage.deactivateEnvironment(projectId);
      
      // 删除项目
      this.dataStorage.deleteProject(projectId);
      
      console.log(`[Switcher3] 删除项目成功: ${project.name}`);
      
      return {
        success: true,
        message: '项目删除成功'
      };
    } catch (error) {
      console.error('[Switcher3] 删除项目失败:', error);
      return {
        success: false,
        message: `删除失败: ${error.message}`
      };
    }
  }

  /**
   * 更新环境配置
   */
  updateEnvironmentConfig(projectId, environment, config) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      // 处理自定义环境
      if (environment.startsWith('custom:')) {
        const ruleId = environment.substring(7);
        const rule = project.customRules.find(r => r.id === ruleId);
        if (!rule) {
          return {
            success: false,
            message: '自定义环境不存在'
          };
        }
        
        // 更新自定义规则的配置
        this.dataStorage.updateCustomRule(projectId, ruleId, { value: config });
        
        console.log(`[Switcher3] 更新自定义环境配置成功: ${project.name} - ${rule.name}`);
        
        return {
          success: true,
          message: '配置更新成功'
        };
      }

      // 处理标准环境
      if (environment !== 'test' && environment !== 'production') {
        return {
          success: false,
          message: '无效的环境类型'
        };
      }

      // 更新环境配置
      const updates = {
        environments: {
          ...project.environments,
          [environment]: config
        }
      };
      
      this.dataStorage.updateProject(projectId, updates);
      
      console.log(`[Switcher3] 更新环境配置成功: ${project.name} - ${environment}`);
      
      return {
        success: true,
        message: '配置更新成功'
      };
    } catch (error) {
      console.error('[Switcher3] 更新环境配置失败:', error);
      return {
        success: false,
        message: `更新失败: ${error.message}`
      };
    }
  }

  /**
   * 激活环境
   */
  async activateEnvironment(projectId, environment) {
    try {
      console.log(`[Switcher3] 激活环境: ${projectId} - ${environment}`);
      
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      // 检查环境是否存在且已配置
      if (environment === 'test' || environment === 'production') {
        const config = project.environments[environment];
        if (!config || !config.trim()) {
          return {
            success: false,
            message: `${environment === 'test' ? '测试' : '生产'}环境配置为空`
          };
        }
      } else if (environment.startsWith('custom:')) {
        const ruleId = environment.substring(7);
        const rule = project.customRules.find(r => r.id === ruleId);
        if (!rule || !rule.value || !rule.value.trim()) {
          return {
            success: false,
            message: '自定义规则配置为空'
          };
        }
      } else {
        return {
          success: false,
          message: '无效的环境类型'
        };
      }

      // 使用数据存储来管理激活状态
      // 先停用当前项目的所有环境
      this.dataStorage.deactivateEnvironment(projectId);
      
      // 激活新环境
      this.dataStorage.activateEnvironment(projectId, environment);
      
      console.log(`[Switcher3] 环境激活成功: ${projectId} - ${environment}`);
      
      return {
        success: true,
        message: '环境激活成功'
      };
      
    } catch (error) {
      console.error('[Switcher3] 激活环境失败:', error);
      return {
        success: false,
        message: `激活失败: ${error.message}`
      };
    }
  }

  /**
   * 停用环境
   */
  async deactivateEnvironment(projectId) {
    try {
      console.log(`[Switcher3] 停用环境: ${projectId}`);
      
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      // 停用环境
      this.dataStorage.deactivateEnvironment(projectId);
      
      console.log(`[Switcher3] 环境停用成功: ${projectId}`);
      
      return {
        success: true,
        message: '环境停用成功'
      };
      
    } catch (error) {
      console.error('[Switcher3] 停用环境失败:', error);
      return {
        success: false,
        message: `停用失败: ${error.message}`
      };
    }
  }

  /**
   * 添加自定义规则
   */
  addCustomRule(projectId, name, value) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      if (!name || !name.trim()) {
        return {
          success: false,
          message: '规则名称不能为空'
        };
      }

      if (!value || !value.trim()) {
        return {
          success: false,
          message: '规则内容不能为空'
        };
      }

      name = name.trim();
      value = value.trim();

      // 检查名称是否已存在
      if (project.customRules.some(rule => rule.name === name)) {
        return {
          success: false,
          message: '规则名称已存在'
        };
      }

      const rule = this.dataStorage.addCustomRule(projectId, name, value);
      
      console.log(`[Switcher3] 添加自定义规则成功: ${project.name} - ${name}`);
      
      return {
        success: true,
        data: rule,
        message: '规则添加成功'
      };
    } catch (error) {
      console.error('[Switcher3] 添加自定义规则失败:', error);
      return {
        success: false,
        message: `添加失败: ${error.message}`
      };
    }
  }

  /**
   * 更新自定义规则
   */
  updateCustomRule(projectId, ruleId, name, value) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      if (!name || !name.trim()) {
        return {
          success: false,
          message: '规则名称不能为空'
        };
      }

      if (!value || !value.trim()) {
        return {
          success: false,
          message: '规则内容不能为空'
        };
      }

      name = name.trim();
      value = value.trim();

      const rule = project.customRules.find(r => r.id === ruleId);
      if (!rule) {
        return {
          success: false,
          message: '规则不存在'
        };
      }

      // 检查名称是否已存在（排除自己）
      if (project.customRules.some(r => r.id !== ruleId && r.name === name)) {
        return {
          success: false,
          message: '规则名称已存在'
        };
      }

      this.dataStorage.updateCustomRule(projectId, ruleId, name, value);
      
      console.log(`[Switcher3] 更新自定义规则成功: ${project.name} - ${name}`);
      
      return {
        success: true,
        message: '规则更新成功'
      };
    } catch (error) {
      console.error('[Switcher3] 更新自定义规则失败:', error);
      return {
        success: false,
        message: `更新失败: ${error.message}`
      };
    }
  }

  /**
   * 删除自定义规则
   */
  deleteCustomRule(projectId, ruleId) {
    try {
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      const rule = project.customRules.find(r => r.id === ruleId);
      if (!rule) {
        return {
          success: false,
          message: '规则不存在'
        };
      }

      // 如果规则正在使用，先停用
      const activeEnvs = this.dataStorage.getActiveEnvironments();
      const activeCustomRule = activeEnvs.find(env => 
        env.projectId === projectId && env.environment === `custom:${ruleId}`
      );
      
      if (activeCustomRule) {
        this.dataStorage.deactivateEnvironment(projectId);
      }

      this.dataStorage.deleteCustomRule(projectId, ruleId);
      
      console.log(`[Switcher3] 删除自定义规则成功: ${project.name} - ${rule.name}`);
      
      return {
        success: true,
        message: '规则删除成功'
      };
    } catch (error) {
      console.error('[Switcher3] 删除自定义规则失败:', error);
      return {
        success: false,
        message: `删除失败: ${error.message}`
      };
    }
  }

  /**
   * 激活自定义规则
   */
  async activateCustomRule(projectId, ruleId) {
    try {
      console.log(`[Switcher3] 激活自定义规则: ${projectId} - ${ruleId}`);
      
      const project = this.dataStorage.getProject(projectId);
      if (!project) {
        return {
          success: false,
          message: '项目不存在'
        };
      }

      const rule = project.customRules.find(r => r.id === ruleId);
      if (!rule) {
        return {
          success: false,
          message: '规则不存在'
        };
      }

      if (!rule.value || !rule.value.trim()) {
        return {
          success: false,
          message: '规则内容为空'
        };
      }

      // 激活自定义规则
      return await this.activateEnvironment(projectId, `custom:${ruleId}`);
      
    } catch (error) {
      console.error('[Switcher3] 激活自定义规则失败:', error);
      return {
        success: false,
        message: `激活失败: ${error.message}`
      };
    }
  }

  /**
   * 获取统计信息
   */
  getStats() {
    try {
      const projects = this.dataStorage.getProjectList();
      const activeEnvironments = this.dataStorage.getActiveEnvironments();
      
      return {
        success: true,
        data: {
          totalProjects: projects.length,
          activeEnvironments: activeEnvironments.length,
          projects: projects.map(p => ({
            id: p.id,
            name: p.name,
            hasTestConfig: !!(p.environments.test && p.environments.test.trim()),
            hasProductionConfig: !!(p.environments.production && p.environments.production.trim()),
            customRulesCount: p.customRules.length,
            activeEnvironment: activeEnvironments.find(env => env.projectId === p.id)?.environment || null
          }))
        }
      };
    } catch (error) {
      console.error('[Switcher3] 获取统计信息失败:', error);
      return {
        success: false,
        message: `获取失败: ${error.message}`
      };
    }
  }

  /**
   * 获取激活的环境列表
   */
  getActiveEnvironments() {
    try {
      const activeEnvironments = this.dataStorage.getActiveEnvironments();
      const result = activeEnvironments.map(env => {
        const project = this.dataStorage.getProject(env.projectId);
        return {
          projectId: env.projectId,
          projectName: project ? project.name : 'Unknown',
          environment: env.environment,
          activatedAt: env.activatedAt
        };
      });
      
      return {
        success: true,
        data: result
      };
    } catch (error) {
      console.error('[Switcher3] 获取激活环境失败:', error);
      return {
        success: false,
        message: `获取失败: ${error.message}`
      };
    }
  }

  /**
   * 停用所有环境
   */
  async deactivateAllEnvironments() {
    try {
      console.log('[Switcher3] 停用所有环境');
      
      const activeEnvironments = this.dataStorage.getActiveEnvironments();
      
      for (const env of activeEnvironments) {
        this.dataStorage.deactivateEnvironment(env.projectId);
      }
      
      console.log(`[Switcher3] 已停用 ${activeEnvironments.length} 个环境`);
      
      return {
        success: true,
        message: `已停用 ${activeEnvironments.length} 个环境`
      };
      
    } catch (error) {
      console.error('[Switcher3] 停用所有环境失败:', error);
      return {
        success: false,
        message: `停用失败: ${error.message}`
      };
    }
  }

  /**
   * 重置所有数据
   */
  resetAllData() {
    try {
      console.log('[Switcher3] 重置所有数据');
      
      this.dataStorage.resetData();
      
      console.log('[Switcher3] 数据重置完成');
      
      return {
        success: true,
        message: '数据重置成功'
      };
    } catch (error) {
      console.error('[Switcher3] 重置数据失败:', error);
      return {
        success: false,
        message: `重置失败: ${error.message}`
      };
    }
  }

  /**
   * 获取插件信息
   */
  getInfo() {
    return {
      success: true,
      data: {
        name: 'Switcher3',
        version: '1.0.0',
        description: 'Whistle多项目环境配置管理插件',
        author: 'Your Name'
      }
    };
  }

  /**
   * 健康检查
   */
  healthCheck() {
    try {
      // 检查数据存储是否正常
      this.dataStorage.getProjectList();
      
      return {
        success: true,
        data: {
          status: 'healthy',
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('[Switcher3] 健康检查失败:', error);
      return {
        success: false,
        data: {
          status: 'unhealthy',
          error: error.message,
          timestamp: new Date().toISOString()
        }
      };
    }
  }
}

module.exports = ProjectManager;